package com.cory.module.oplog.core;

import java.util.Collection;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cory.boot.base.BaseService;
import com.cory.boot.domain.enumdef.EState;
import com.cory.utils.bean.ReflectioUtils;

/**
 * @author xiongcong
 * @date 2022-01-10
 */
public class OpLogBaseService <M extends BaseMapper<T>, T> extends BaseService<M, T> {
    
    public boolean save2Log(T entity) {
        
        boolean result = super.save(entity);
        
        OpLogClient.log4Save(entity);
        return result;
    }

    public boolean updateById2Log(T entity) {
        Integer id = (Integer)ReflectioUtils.getFieldValue(entity, "id");
        T tmp = super.getById(id);
        
        boolean result = super.updateById(entity);
        
        OpLogClient.log4Update(tmp, entity);
        return result;
    }
    
    public boolean delete2Log(Integer id) {
        return this.updateState2Log(id, EState.DELETE.key);
    }
    
    public boolean enable2Log(Integer id) {
        return this.updateState2Log(id, EState.ENABLE.key);
    }
    
    public boolean disable2Log(Integer id) {
        return this.updateState2Log(id, EState.DISABLE.key);
    }
    
    public boolean updateState2Log(Integer id, Integer state) {
        boolean result = super.updateState(id, state);
        
        OpLogClient.log4State(super.getById(id), state);
        return result;
    }
    
    public boolean deleteByIds2Log(List<Integer> ids) {
        return this.updateStateByIds2Log(ids, EState.DELETE.key);
    }
    
    public boolean enableByIds2Log(List<Integer> ids) {
        return this.updateStateByIds2Log(ids, EState.ENABLE.key);
    }
    
    public boolean disableByIds2Log(List<Integer> ids) {
        return this.updateStateByIds2Log(ids, EState.DISABLE.key);
    }
    
    @SuppressWarnings("rawtypes")
    public boolean updateStateByIds2Log(List<Integer> ids, Integer state) {
        boolean result = super.updateStateByIds(ids, state);
        
        Collection collection = super.listByIds(ids);
        for (Object item : collection) {
            OpLogClient.log4State(item, state);
        }
        return result;
    }
}
